package com.common.link.service;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.common.link.model.RemoteOfficeVO;
import com.common.link.model.RemoteResult;
import com.google.common.collect.Lists;
import com.common.utils.constant.Constants;
import com.common.utils.tool.StringUtil;
import com.common.link.config.LinkConfig;
import com.common.link.model.RemoteUserVO;
import com.service.http.service.HttpService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 描述：
 *
 * @author xianggj
 * @Date 2022/2/14 17:19
 **/
public class RemoteUserService {

    @Autowired
    private HttpService httpService;

    @Autowired
    private LinkConfig linkConfig;

    /**
     * 获取当前用户
     * @param token
     * @return
     */
    public RemoteUserVO getCurrentUser(String token){
        String getUserUrl = linkConfig.getGetUser();
        HttpHeaders headers = new HttpHeaders();
        headers.add(LinkConfig.HEADER, token);
        String s = httpService.get(getUserUrl, headers);
        RemoteResult remoteResult = JSON.parseObject(s, RemoteResult.class);
        if (remoteResult == null){
            return null;
        }
        String data = remoteResult.getData();
        if (data == null ){
            return null;
        }
        JSONObject jsonObject = JSON.parseObject(data);
        JSONObject office = jsonObject.getJSONObject("office");
        RemoteUserVO remoteUserVO = RemoteUserVO.builder()
                .id(jsonObject.getString("id"))
                .loginName(jsonObject.getString("loginName"))
                .name(jsonObject.getString("name"))
                .officeId(office==null?null:office.getString("id"))
                .officeName(office==null?null:office.getString("name"))
                .build();
        return remoteUserVO;
    }

    /**
     * 获取当前用户
     * @return
     */
    public List<RemoteUserVO> getUserList(){
        String userListUrl = linkConfig.getGetUserList();
        String s = httpService.get(userListUrl);
        RemoteResult remoteResult = JSON.parseObject(s, RemoteResult.class);
        List<RemoteUserVO> resList = new ArrayList<>();
        if (remoteResult == null){
            return resList;
        }
        String data = remoteResult.getData();
        if (data == null ){
            return resList;
        }
        JSONArray jsonArray = JSON.parseArray(data);
        for (Object o : jsonArray) {
            JSONObject jsonObject = (JSONObject) o;
            JSONObject office = jsonObject.getJSONObject("office");
            RemoteUserVO remoteUserVO = RemoteUserVO.builder()
                    .id(jsonObject.getString("id"))
                    .loginName(jsonObject.getString("loginName"))
                    .name(jsonObject.getString("name"))
                    .officeId(office == null ? null : office.getString("id"))
                    .officeName(office == null ? null : office.getString("name"))
                    .build();
            resList.add(remoteUserVO);
        }
        return resList;
    }
    /**
     * 获取当前用户
     * @return
     */
    public List<RemoteUserVO> getUserList(String dids, String searchKey){
        List<RemoteUserVO> userList = getUserList();
        if (StringUtil.isNotBlank(dids)){
            String[] ids = StrUtil.split(dids, Constants.COMMA);
            userList = userList.stream().filter(e->
                ArrayUtil.contains(ids, e.getOfficeId())
            ).collect(Collectors.toList());
        }
        if (StringUtil.isNotBlank(searchKey)){
            userList = userList.stream().filter(e->
                    StrUtil.contains(e.getName(), searchKey) ||
                            StrUtil.contains(e.getOfficeName(), searchKey)
            ).collect(Collectors.toList());
        }
        return userList;
    }

    /**
     * 获取当前用户
     * @return
     */
    public List<RemoteOfficeVO> getOfficeList(){
        String officeList = linkConfig.getGetOfficeList();
        String s = httpService.get(officeList);
        RemoteResult remoteResult = JSON.parseObject(s, RemoteResult.class);
        List<RemoteOfficeVO> resList = new ArrayList<>();
        if (remoteResult == null){
            return resList;
        }
        String data = remoteResult.getData();
        if (data == null ){
            return resList;
        }
        Map<String, List<RemoteOfficeVO>> map = new HashMap<>();
        JSONArray jsonArray = JSON.parseArray(data);
        for (Object o : jsonArray) {
            JSONObject jsonObject = (JSONObject) o;
            String parentId = jsonObject.getString("parentId");
            RemoteOfficeVO remoteUserVO = RemoteOfficeVO.builder()
                    .id(jsonObject.getString("id"))
                    .name(jsonObject.getString("name"))
                    .build();
            if (map.containsKey(parentId)){
                map.get(parentId).add(remoteUserVO);
            } else {
                map.put(parentId, Lists.newArrayList(remoteUserVO));
            }
        }
        List<RemoteOfficeVO> remoteOfficeVOS = map.get("0");
        setRemoteOfficeVOS(map, remoteOfficeVOS);
        //根目录
        resList.addAll(remoteOfficeVOS);
        return resList;
    }

    @NotNull
    private void setRemoteOfficeVOS(Map<String, List<RemoteOfficeVO>> map,
                                                    List<RemoteOfficeVO> remoteOfficeVOS) {
        for (RemoteOfficeVO remoteOfficeVO: remoteOfficeVOS) {
            if (map.containsKey(remoteOfficeVO.getId())){
                List<RemoteOfficeVO> children = map.get(remoteOfficeVO.getId());
                setRemoteOfficeVOS(map, children);
                remoteOfficeVO.setChildren(children);
            }
        }
    }

    public Integer getErrorCode(){
        return linkConfig.getLoginFailCode();
    }
}
